package com.juyu.miliao.common.util;

import com.juyu.miliao.common.constant.AppPackageIdConstant;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jh
 * 2018/9/18
 */
public class VerifyUtil {

    /**
     * 验证通用请求头
     *
     * @param request request
     * @return CommonHead
     */
    public static CommonHead verifyCommonHead(HttpServletRequest request) throws ConsumeRuntimeException {
        CommonHead com = new CommonHead();
        //版本
        String version = request.getHeader("versionNum");
        if (CommonUtil.isEmptyString(version)) {
            throw new ConsumeRuntimeException("版本号不能为空");
        }
        //手机系统
        String phone = request.getHeader("phoneSystem");
        if (phone == null) {
            throw new ConsumeRuntimeException("系统类型不能为空");
        }
        if (!(phone.equals("1") || phone.equals("2"))) {
            throw new ConsumeRuntimeException("系统类型只能为1-安卓,2-IOS");
        }
        //渠道号
        String channel = request.getHeader("channel");
        if (CommonUtil.isEmptyString(channel)) {
            throw new ConsumeRuntimeException("channel不能为空");
        }

        //应用标识,如果为空则是老版本的,要兼容
        String appPackageId = CommonUtil.null2String(request.getHeader("appPackageId"));
        if (CommonUtil.isEmptyString(appPackageId)) {
            appPackageId = AppPackageIdConstant.DEFAULT_APP_PACKAGE_ID;
        }

        //线上线下 兼容老版本 默认为null 具体逻辑全用 PackageOnlineService
        String stringOnline = request.getHeader("online");
        if (CommonUtil.isEmptyString(stringOnline)) {
            com.setOnline(EnumType.ONLINE.state);
        } else{
            com.setOnline(Integer.parseInt(stringOnline));
        }

        String deviceNo =  request.getHeader("deviceNo");
        if(deviceNo==null){
            deviceNo="";
        }
        com.setVersionNum(version.trim());
        com.setPhoneSystem(phone.trim());
        com.setChannel(channel.trim());
        com.setAppPackageId(appPackageId.trim());
        com.setActiveUserId(request.getHeader("activeUserId"));
        com.setVerifyOpenId(request.getHeader("verifyOpenId"));
        com.setIp(ServletTool.getRemoteHost(request));
        com.setDeviceNo(deviceNo);
        com.setRanReqPk(request.getHeader("ranReqPk"));
        return com;
    }
}
